//
//  BK_My_Cup_Used_collectionCell.m
//  bestkeep
//
//  Created by TOPTEAM on 2017/2/9.
//  Copyright © 2017年 utouu. All rights reserved.
//

#import "BK_My_Cup_Used_collectionCell.h"
#import "BK_My_Cup_Used_tabVCell.h"
#import "BK_my_couponCommon.h"
#import "BKMyCommon.h"
#import "UIView+ParentController.h"


#import "BK_my_CouponModel.h"
#import "BKRefreshControl.h"
#import "MJRefresh.h"
#import "Mediator+BKGD.h"
#import "Mediator+BKClassify.h"
#import "BK_my_CouponTextField.h"
#import "ExceptionView.h"


#import "BK_my_CouponNoDataView.h"
@interface BK_My_Cup_Used_collectionCell ()

@property (nonatomic, strong) BK_my_CouponTextField *couponTextField;
@property (nonatomic, strong) UIButton *button;

@property (nonatomic, strong) ExceptionView *exceptionView;

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) NSString *useType;
@property (nonatomic, strong) BK_my_CouponNoDataView * unUse_noDataView;

@end

@implementation BK_My_Cup_Used_collectionCell
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self){
        self.backgroundColor = RGBCOLOR(242, 242, 242, 1);
        [self setProperty];
        [self initView];
        [self checkNetWorking];
    }
    return self;
}

#pragma mark=============setProperty=============
-(void)setProperty{
    self.pageSize    = 20;
    self.currentPage = 1;
    self.useType     = @"0";
}
#pragma mark=============loadData=============
-(void)BK_My_Cup_Used_loadData{
    [self dataWithType:self.useType pageSize:[NSString stringWithFormat:@"%@", @(self.pageSize)] pageno:[NSString stringWithFormat:@"%@", @(self.currentPage)]];
}
- (void)initView{
    
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 56)];
    headerView.backgroundColor = RGBCOLOR(242, 242, 242, 1);
    
    _couponTextField = [[BK_my_CouponTextField alloc] initWithFrame:CGRectZero];
    _couponTextField.layer.cornerRadius = 5;
    [_couponTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    _couponTextField.font = [UIFont systemFontOfSize:14];
    _couponTextField.backgroundColor = [UIColor whiteColor];
    _couponTextField.placeholder = @"请输入6位兑换码(字母区分大小写)";
    [_couponTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
    [headerView addSubview:self.couponTextField];
    [_couponTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(headerView.mas_left).offset(ApplicationBackGauge);
        make.top.mas_equalTo(headerView.mas_top).offset(10);
        make.height.mas_equalTo(36);
        make.width.mas_equalTo(SCREENWIDTH - 55-ApplicationBackGauge*2);
    }];
    
    [self addSubview:headerView];
    _button = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.couponTextField.frame) + 5, 10, 50, 32)];
    [_button setTitle:@"兑换" forState:UIControlStateNormal];
    [headerView addSubview:_button];
    [_button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(headerView.mas_right).offset(-ApplicationBackGauge);
        make.top.mas_equalTo(headerView.mas_top).offset(10);
        make.height.mas_equalTo(36);
        make.left.mas_equalTo(_couponTextField.mas_right).offset(10);
    }];
    
    _button.layer.cornerRadius = 5;
    [_button addTarget:self action:@selector(exchangeButton:) forControlEvents:UIControlEventTouchUpInside];
    _button.titleLabel.font = [UIFont systemFontOfSize:14];
    _button.backgroundColor = BK_MY_COLOR_01;
    
    
    
    
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 56, ScreenWidth, ScreenHeight-100-56) style:UITableViewStylePlain];
    
    [self addSubview:_tableView];
    
    _tableView.backgroundColor=RGBCOLOR(242, 242, 242, 1);
    
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];
    v.backgroundColor = [UIColor clearColor];
    _tableView.tableFooterView = v;
    
    
    _unUse_noDataView = [[BK_my_CouponNoDataView alloc] initWithFrame:CGRectMake(0, 46, ScreenWidth, ScreenHeight-64-46)];
    _unUse_noDataView.backgroundColor = RGBCOLOR(242, 242, 242, 1);
    [self addSubview:_unUse_noDataView];
    _unUse_noDataView.hidden=YES;
    
    
}
//第section分区一共有多少行

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

//创建第section分区第row行的UITableViewCell对象(indexPath包含了section和row)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
   
    
    BK_My_Cup_Used_tabVCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BK_My_Cup_Used_tabVCell"];
    if (cell == nil) {
        cell = [[BK_My_Cup_Used_tabVCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BK_My_Cup_Used_tabVCell"];
    }
    cell.unUsedModel = self.dataArr[indexPath.row];
    return cell;

}

#pragma mark - tableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 101;
}




#pragma mark - TableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
#pragma mark - tableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0;
}

#pragma mark===================Footer===================
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
//
//}

#pragma mark===================Header===================
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//
//}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BK_my_CouponModel *model = self.dataArr[indexPath.row];
    if (![model.viewGoodsInfoStr isEqualToString:@""] && model.sprticific == 1) {
        UIViewController *vc = [[Mediator sharedInstance] BKGD_goodsDetailViewController:model.goodsId saleTypes:nil];
        [[UIView BKcurrentViewController].navigationController pushViewController:vc animated:YES];
        
    } else if (model.sprticific == 2 && ![model.categoryId isEqualToString:@""]) {
        
        //        @"currentPage":[NSString stringWithFormat:@"%ld",(long)page],//当前查询页
        //        @"channelType":channelType,//xxx商品渠道[1:国内商品，2：跨境淘，3：有糖自营，4：有糖众筹]
        //        @"categoryId":categoryId,//商品分类ID
        //        @"keyWord":keyWord,//搜索关键字
        //        @"filterTerms":filterTerms,//商品过滤项[-1:全部，0：推荐，1：新品，2：热门]
        //        @"order_key":order,//排序字段[价格：price]
        //        @"sort_name":order,//排序名称[asc:升序，desc降序]
        //  ElHD-3VASYWY_7QDPj39Wg
        
//        UIViewController *vc = [[Mediator sharedInstance] ClassfiyIntorecordPushInformationWithFilterTerms:@"-1" categotyId:model.categoryId channelType:@"" orderKey:@"" currentPage:0 keyWord:@"" order:@""];
        UIViewController *vc = [[Mediator sharedInstance] classifyWithFilterTerms:@"-1" categotyId:model.categoryId channelType:@"" orderKey:@"" currentPage:0 keyWord:@"" order:@"" classifyType:@"1"];
        
        //        UIViewController *vc = [[Mediator sharedInstance] HomeIntorecordPushInformationWithFilterTerms:@"-1" categotyId:model.categoryId channelType:@"" orderKey:@"" currentPage:0 keyWord:@"" order:@""];
        [[UIView BKcurrentViewController].navigationController pushViewController:vc animated:YES];
    } else {
        return;
    }
}




//加载数据方法
- (void)dataWithType:(NSString *)useType pageSize:(NSString *)page_size pageno:(NSString *)page_no {
    
    
    [BKIndicationView showInView:self];
    [BK_my_couponCommon getVoucherShopping:useType pagesize:page_size pageno:page_no callback:^(id obj, NSError *error) {
        if (error) {
            if(!self.exceptionView && error) {
                self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeServerError];
                
                ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:ExceptionCodeTypeServerError handler:^(ExceptionViewAction *action) {
                    [BKIndicationView showInView:self];
                    [self BK_My_Cup_Used_loadData];
                }];
                
                [self.exceptionView addAction:retryAction];
                [self.exceptionView showInView:self];
                
                [BKIndicationView dismiss];
            }else{
                [BKIndicationView dismiss];
            }
            
        } else {
            if(self.exceptionView) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
            }
            [BKIndicationView dismiss];
            NSMutableArray *muArray = [NSMutableArray array];
            NSInteger total = 0;
            NSDictionary *dict = obj;
            NSArray *arr = dict[@"rows"];
        
            for (NSDictionary *subDict in arr) {
                BK_my_CouponModel *model = [self dictionary:subDict dic:dict integer:total];
                [muArray addObject:model];
            }

            [self.dataArr removeAllObjects];
            self.dataArr = muArray;

            if (muArray.count == 0) {
                _unUse_noDataView.hidden=NO;
            } else {
                _unUse_noDataView.hidden=YES;
            }
        }
        [_tableView.mj_footer endRefreshing];
        [_tableView.mj_header endRefreshing];
        [_tableView reloadData];
    }];
}


- (BK_my_CouponModel *)dictionary:(NSDictionary *)subDict dic:(NSDictionary *)dict integer:(NSInteger)total {
    BK_my_CouponModel *model = [[BK_my_CouponModel alloc]init];
    model.couponId  = subDict[@"couponId"];
    model.goodsId = subDict[@"goodsId"];
    model.couponTypeStr = subDict[@"couponTypeStr"];
    model.goodsNo = subDict[@"goodsNo"];
    model.invalidTimeStr = subDict[@"invalidTimeStr"];
    model.reduceCost = subDict[@"reduceCost"];
    model.remainingWarning = subDict[@"remainingWarning"];
    model.viewGoodsInfoStr = subDict[@"viewGoodsInfoStr"];
    model.viewCategoryInfoStr = subDict[@"viewCategoryInfoStr"];
    model.status = [NSString stringWithFormat:@"%@",subDict[@"status"]];
    model.pagesize =[NSString stringWithFormat:@"%@", dict[@"pagesize"]];
    model.pageno = [NSString stringWithFormat:@"%@",dict[@"pageno"]];
    model.total = [NSString stringWithFormat:@"%@",dict[@"total"]];
    model.use_Type = [NSString stringWithFormat:@"%@",dict[@"useType"]];
    model.sprticific = [subDict[@"sprticific"] integerValue];
    model.categoryId = subDict[@"categoryId"];
    total = [dict[@"total"] doubleValue];
    return model;
}


- (void)exchangeButton:(UIButton *)sender {
    if (_couponTextField.text.length < 6) {
        [HUD showMessage:@"请输入6位兑换码"];
        return;
    }
    _button.enabled = NO;
    [self exchangeCouponByCouponNo:_couponTextField.text];
}

-(void)exchangeCouponByCouponNo:(NSString *)couponNo{
    [self endEditing:YES];
    NSString *s = @"^[A-Za-z0-9]+$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",s];
    BOOL b = [predicate evaluateWithObject:couponNo];
    
    if (b == YES && couponNo.length == 6) {
        [BKIndicationView showInView:self];
        [BK_my_couponCommon exchangeCouponByCouponNO:couponNo mycallBack:^(id obj, NSError *error) {
            _button.enabled = YES;
            [BKIndicationView dismiss];
            if ([obj[@"success"] boolValue] == 1) {
                NSDictionary *dictionary = obj;
                if ([[NSString stringWithFormat:@"%@", dictionary[@"success"]] isEqualToString:@"1"]) {
                    _couponTextField.text = nil;
                    [HUD showSuccessMessage:@"兑换成功"];
                    [self dataWithType:@"0" pageSize:[NSString stringWithFormat:@"%@", @(20)] pageno:[NSString stringWithFormat:@"%@", @(1)]];
                }
            } else {
                [HUD showErrorMessage:obj[@"msg"]];
            }
        }];
    }else{
        _button.enabled = YES;
        [HUD showErrorMessage:@"请检查兑换码是否正确"];
    }
}


-(void)textFieldDidChange:(UITextField*)textFidld{
    if (textFidld == _couponTextField) {
        if (textFidld.text.length > 10) {
            textFidld.text = [textFidld.text substringToIndex:10];
        }
    }
}

-(void)checkNetWorking {
    RequestReachabilityStatus status = [RequestManager reachabilityStatus];
    switch (status) {
        case RequestReachabilityStatusReachableViaWiFi:
        case RequestReachabilityStatusReachableViaWWAN: {
            [self BK_My_Cup_Used_loadData];
            
        }
            break;
            
        default: {
            [BKIndicationView dismiss];
            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoNetwork];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeNoNetwork handler:^(ExceptionViewAction *action) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
                [self checkNetWorking];
            }];
            [self.exceptionView addAction:action];
            [self.exceptionView showInView:self];
            
        }
            break;
    }
}


@end
